/**
 * Created by haua on 17/7/5.
 */

//拖动事件
(function () {
    var state = {
            START : 1,//手指接触到屏幕
            END : 2, //松开手指
            UP : 11,//当前点比开始点偏上
            RIGHT : 12,//右
            DOWN : 13,//下
            LEFT : 14//左
        },
        threshold = 5;//手指移动多少px才算是拖拽。touchstart和touchend时，会无视此参数，肯定会回调
    /*
     * 回调函数的参数
     * @param object 各个参数，当前点的x，y值
     * */
    function HSlideEvent(fn,tar){
        if(!fn||typeof fn !=='function'){
            console.error('[HSlideEvent]传入的参数不是函数');
            return
        }

        tar = tar||document;

        var SP,LP,NP,LT,//开始点，上一个点，现在的点，上一个时间
            nowState = state.END;//手指移动距离超过下面设定的，此值才为true
        tar.addEventListener('touchstart',function (e) {
            SP = LP = NP = getP(e.touches[0]);
            nowState = state.START;
            LT = new Date();
            callBack()
        },false);
        tar.addEventListener('touchmove',function (e) {
            //去掉手机滑动默认行为
            e.preventDefault();

            NP = getP(e.touches[0]);
            if(nowState === state.START){
                var d = {
                        x : NP.x - SP.x,
                        y : NP.y - SP.y
                    },
                    absD = {
                        x : Math.abs(d.x),
                        y : Math.abs(d.y)
                    };
                if(absD.x>threshold||absD.y>threshold){
                    nowState = absD.x>=absD.y?(d.x>0?state.RIGHT:state.LEFT):(d.y>0?state.DOWN:state.UP)
                }
            }
            if(nowState!==state.START&&nowState!==state.END){
                callBack()
            }
            LP = NP;
        }, { passive: false });
        tar.addEventListener('touchend',function () {
            nowState = state.END;
            callBack();
        },false);

        //计算当前状态并返回
        function callBack() {
            var d = {
                    x : NP.x - LP.x,
                    y : NP.y - LP.y
                },
                NT = new Date(),
                IT = NT - LT;

            LT = NT;

            fn({
                startPoint : SP,
                lastPoint : LP,
                nowPoint : NP,
                move : d,
                intervalTime:IT,
                state : nowState
            })
        }

        //提取touch里的xy数据
        function getP(touch) {
            return {
                x:touch.pageX,
                y:touch.pageY
            }
        }
    }

    HSlideEvent.STATE = state;

    window.HSlideEvent = HSlideEvent;
}());